package emulator;

import java.io.FileInputStream;

import emulator.GUI.VicUI;
import emulator.cbm.basic.BasicHelper;
import emulator.hardware.bus.VideoBus;
import emulator.hardware.memory.MemoryBlock;
import emulator.hardware.nmos6502.Cpu6502;
import emulator.hardware.video.Vic6561;
import emulator.small.Board;

public class VicSmall {
	private static final String kernal_rom = "/sdcard/vicoid20/pal.bin";
	private static final String character_rom = "/sdcard/vicoid20/characters.901460-03.bin";
	private static VicSmall instance = new VicSmall();
	private Cpu6502 cpu;
	private Board board = null;

	public static VicSmall getInstance()
	{
		return instance;
	}
	
	/**
	 * @param args
	 * @throws EmulatorException 
	 */
	public void initialise() throws Exception {
		MemoryBlock memory = new MemoryBlock(65536);
		memory.loadFromStream(new FileInputStream(character_rom), 0x8000, 0x1000);
		memory.loadFromStream(new FileInputStream(kernal_rom), 0xC000, 0x4000);
		
		BasicHelper.setMemoryBlock(memory);
		
		cpu = new Cpu6502();
		Vic6561 vic = new Vic6561();

		board = new Board();
		board.setMemory(memory);
		board.setIrqLines(cpu.getNmiIn(), cpu.getIrqIn());
		board.setVic(vic);
		
		cpu.attach(board.getBus(), board.getCpuClock());
		cpu.reset();
		cpu.start();

		vic.attach(new VideoBus(memory), board.getVicClock());
		vic.start();
		
/*		KeyboardMatrix matrix = new KeyboardMatrix();
		matrix.attachToVia(via2, via1);
		VicUI.setMatrix(matrix); */
		VicUI.setKeyboardMapName("/sdcard/vicoid20/keymap.ini");

/*		Joystick joystick = new Joystick();
		joystick.attachToVia(via2, via1);
		VicUI.setJoystick(joystick); */
		
		VicUI.setClock(board.getCpuClock());
		VicUI.setCpu(cpu);
		VicUI.initialiseVic();
	}
	
	public void startCpu() {
		getCpu().go();
	}

	public void printState() {
		try {
			getCpu().halt();
			getCpu().waitForHalt();
			getCpu().printState(System.out);
		} catch (EmulatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void resetCpu() {
		try {
			getCpu().halt();
			getCpu().waitForHalt();
			getCpu().reset();
		} catch (EmulatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Cpu6502 getCpu() {
		return cpu;
	}

	public Board getBoard() {
		return board;
		
	}
}
